/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.cookbooks;

import com.huawei.cookbooks.database.Form;
import com.huawei.cookbooks.database.FormDatabase;
import com.huawei.cookbooks.utils.ComponentProviderUtils;
import com.huawei.cookbooks.utils.DatabaseUtils;

import com.huawei.cookbooks.utils.DateUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.FormException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.ComponentProvider;
import ohos.ai.tts.TtsClient;
import ohos.ai.tts.TtsListener;
import ohos.ai.tts.TtsParams;
import ohos.ai.tts.constants.TtsEvent;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmPredicates;
import ohos.event.notification.NotificationRequest;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.PacMap;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Time PA
 */
public class TimerAbility extends Ability {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");
    private static final long SEND_PERIOD = 1000L;
    private static final int NOTICE_ID = 1005;
    private DatabaseHelper helper = new DatabaseHelper(this);
    private OrmContext connect;
    private boolean initTtsResult;

    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private TtsListener ttsListener = new TtsListener() {

        @Override
        public void onEvent(int eventType, PacMap pacMap) {
            HiLog.info(LABEL_LOG, "onEvent...");
            // 定义TTS客户端创建成功的回调函数
            if (eventType == TtsEvent.CREATE_TTS_CLIENT_SUCCESS) {
                TtsClient.getInstance().release();
                TtsParams ttsParams = new TtsParams();
                ttsParams.setDeviceId(UUID.randomUUID().toString());
                initTtsResult = TtsClient.getInstance().init(ttsParams);
            }
        }

        @Override
        public void onStart(String utteranceId) {
            HiLog.info(LABEL_LOG, "onStart...");
        }

        @Override
        public void onProgress(String utteranceId, byte[] audioData, int progress) {
        }

        @Override
        public void onFinish(String utteranceId) {
            HiLog.info(LABEL_LOG, "onFinish...");
        }

        @Override
        public void onError(String s, String s1) {
            HiLog.info(LABEL_LOG, "onError...");
        }

        @Override
        public void onSpeechStart(String utteranceId) {
            HiLog.info(LABEL_LOG, "onSpeechStart...");
        }

        @Override
        public void onSpeechProgressChanged(String utteranceId, int progress) {
        }

        @Override
        public void onSpeechFinish(String utteranceId) {
            HiLog.info(LABEL_LOG, "onSpeechFinish...");
        }
    };

    @Override
    public void onStart(Intent intent) {
        HiLog.info(LABEL_LOG, "TimerAbility::onStart");
        connect = helper.getOrmContext("FormDatabase", "FormDatabase.db", FormDatabase.class);
        startTimer();
        super.onStart(intent);
        TtsClient.getInstance().create(this, ttsListener);
    }

    private void notice() {
        Calendar now = Calendar.getInstance();

        // 创建通知
        NotificationRequest request = new NotificationRequest(NOTICE_ID);
        request.setAlertOneTime(true);
        NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
        content.setText(dateFormat.format(now.getTime()));
        NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
        request.setContent(notificationContent);
        // 绑定通知
        keepBackgroundRunning(NOTICE_ID, request);

        //播报
        if (initTtsResult) {
            int hour = now.get(Calendar.HOUR_OF_DAY);
            int min = now.get(Calendar.MINUTE);
            int second = now.get(Calendar.SECOND);

            if (second==0) {
                TtsClient.getInstance().speakText(String.format("当前时间%d点%d分", hour, min), null);
            }
        }
    }
    // 卡片更新定时器，每秒更新一次
    private void startTimer() {
        Timer timer = new Timer();
        timer.schedule(
                new TimerTask() {
                    @Override
                    public void run() {
                        updateForms();
                        notice();
                    }
                },
                0,
                SEND_PERIOD);
    }

    private void updateForms() {
        // 从数据库中获取卡片信息
        OrmPredicates ormPredicates = new OrmPredicates(Form.class);
        List<Form> formList = connect.query(ormPredicates);
        // 更新时分秒
        if (formList.size() <= 0) {
            return;
        }
        for (Form form : formList) {
            // 遍历卡片列表更新卡片
            ComponentProvider componentProvider = ComponentProviderUtils.getComponentProvider(form, this);
            try {
                Long updateFormId = form.getFormId();
                updateForm(updateFormId, componentProvider);
            } catch (FormException e) {
                // 删除不存在的卡片
                DatabaseUtils.deleteFormData(form.getFormId(), connect);
                HiLog.error(LABEL_LOG, "onUpdateForm updateForm error");
            }
        }
    }

    @Override
    public void onBackground() {
        super.onBackground();
        HiLog.info(LABEL_LOG, "TimerAbility::onBackground");
    }

    @Override
    public void onStop() {
        TtsClient.getInstance().destroy();
        super.onStop();
        HiLog.info(LABEL_LOG, "TimerAbility::onStop");
    }
}
